import 'dart:async';

import 'package:environmental_les_app/common/net/net.dart';
import 'package:environmental_les_app/common/style/colours.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:flutter_clx_base/utils/string_util.dart';

typedef PhoneNumProvider = String Function();

/// 发送验证码控件
class SendCodeWidget extends StatefulWidget {
  final PhoneNumProvider phoneProvider;
  final String code;
  final Color? color;

  const SendCodeWidget(
    this.code,
    this.phoneProvider, {
    super.key,
    this.color,
  });

  @override
  State<SendCodeWidget> createState() => _SendCodeWidgetState();
}

class _SendCodeWidgetState extends State<SendCodeWidget> {
  static const codeTime = 59; //倒计时时间

  Timer? _countdownTimer;
  String _codeCountdownStr = '获取验证码';
  // 第几次获取
  int _countdownNum = codeTime;
  var defaultColor = Colours.appMain;

  late bool isClickable = true;

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: isClickable ? _onTap : null,
      child: Text(
        _codeCountdownStr,
        style: TextStyle(
          color: widget.color ?? Theme.of(context).primaryColor,
          fontSize: 14.0,
          fontWeight: FontWeight.bold,
          height: 1,
        ),
      ),
    );
  }

  _onTap() {
    isClickable = isMobile(widget.phoneProvider.call());
    if (!isClickable) {
      ToastUtil.showToast("请输入正确的手机号");
      isClickable = true;
      return;
    }
    _setState();
    if (isClickable && (_countdownNum == codeTime)) {
      _onTapCount();
    }
  }

  void _action() {
    isClickable = false;
    _setState();
    defaultColor = const Color(0xFF9B9B9B);
    _codeCountdownStr = '${_countdownNum--}s';
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdownNum > 0) {
        _codeCountdownStr = '${_countdownNum--}s';
      } else {
        _codeCountdownStr = '获取验证码';
        isClickable = true;
        defaultColor = Colours.appMain;
        _countdownNum = codeTime;
        _countdownTimer?.cancel();
      }
      _setState();
    });
  }

  _setState() {
    setState(() {});
  }

  // 不同文字对应不同的操作
  _onTapCount() {
    _getSmsCode();
  }

  // 获取短信验证码
  _getSmsCode() {
    NetUtils.post(ServiceApi.getVCode, data: {
      'phone': widget.phoneProvider.call(),
    }, successCallback: (result) {
      ToastUtil.showToast('获取验证码成功');
      _action();
    });
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    super.dispose();
  }
}
